package tt.dz.biz.service.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.avro.Protocol;
import org.apache.avro.Protocol.Message;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.stereotype.Service;
import tt.dz.biz.dao.user.UserDAOImpl;
import tt.dz.biz.service.card.CardTypeService;
import tt.dz.biz.service.user.UserService;
import tt.dz.common.DZStringUtil;
import tt.dz.common.DzConstants;
import tt.dz.common.DzConstants.CardType;
import tt.dz.common.DzConstants.Common;
import tt.dz.common.DzErrorCode;
import tt.dz.common.DzErrorCode.CommonErrorCode;
import tt.dz.common.DzErrorCode.ExceptionErrorCode;
import tt.dz.common.DzErrorCode.UserErrorCode;
import tt.dz.common.LogUtil;
import tt.dz.common.RPCUtil;
import tt.dz.vo.UserBaseVO;
import tt.dz.vo.UserDetailVO;

@Service("rpcUserInfoService")
public class RPCUserInfoService
  implements RPCBaseService
{
  @Resource(name="userDAO")
  private UserDAOImpl userDAO;
  @Resource(name="cardTypeServiceImpl")
  private CardTypeService cardTypeService;
  @Resource(name="userService")
  private UserService userService;
  
  public Object execute(Protocol.Message message, Object request, Protocol protocol)
    throws Exception
  {
    String name = message.getName();
    Object reqJson = ((GenericRecord)request).get("req");
    String resJson = "";
    if ("updateUser".equals(name)) {
      resJson = updateUser(reqJson.toString());
    } else if ("queryUserDetail".equals(name)) {
      resJson = queryUserDetail(reqJson.toString());
    } else if ("queryUserDetailByCard".equals(name)) {
      resJson = queryUserDetailByCard(reqJson.toString());
    } else if ("userIsExists".equals(name)) {
      resJson = userIsExists(reqJson.toString());
    } else if ("queryCardState".equals(name)) {
      resJson = queryCardState(reqJson.toString());
    } else if ("queryUser".equals(name)) {
      resJson = queryUser(reqJson.toString());
    }
    return resJson;
  }
  
  public String queryUser(String reqJson)
    throws Exception
  {
    JSONObject resObj = new JSONObject();
    JSONObject reqObj = JSON.parseObject(reqJson);
    Integer userType = reqObj.getInteger("user_type");
    if (userType != null) {
      if (!DZStringUtil.verifyValueInEnums(String.valueOf(userType), new String[] { "0", "1", "2" }))
      {
        resObj = RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.CommonErrorCode.PARAM_FORMAT_ERROR.value(), "userType传入格式错误！");
        
        return JSON.toJSONString(resObj);
      }
    }
    try
    {
      List<UserBaseVO> userList = this.userService.queryUserByUserType(userType);
      resObj = RPCUtil.generateResponseObject(Integer.valueOf(1), null, null);
      resObj.put("result", userList);
    }
    catch (Exception e)
    {
      LogUtil.error("客户查询发生异常", e);
      resObj = RPCUtil.generateResponseObject(Integer.valueOf(0), DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value(), "客户查询发生异常");
    }
    return JSON.toJSONString(resObj);
  }
  
  public String updateUser(String reqJson)
    throws Exception
  {
    JSONObject resObj = new JSONObject();
    boolean isCheck = true;
    Integer isSuccess = Integer.valueOf(0);
    StringBuffer errorMsg = new StringBuffer();
    JSONObject reqObj = JSON.parseObject(reqJson);
    
    String userId = reqObj.getString("userId");
    String nickName = reqObj.getString("nickName");
    String userName = reqObj.getString("userName");
    String gender = reqObj.getString("gender");
    

    String districtCode = reqObj.getString("districtCode");
    String addDetail = reqObj.getString("addDetail");
    String longitude = reqObj.getString("longitude");
    String latitude = reqObj.getString("latitude");
    
    String email = reqObj.getString("email");
    if ((userId == null) || ("".equals(userId)))
    {
      errorMsg.append("用户ID不能够为空");
      isCheck = false;
    }
    if ((gender != null) && (!"".equals(gender))) {
      if (!DZStringUtil.verifyValueInEnums(gender, new String[] { "0", "1" }))
      {
        isCheck = false;
        errorMsg.append("性别格式不合法 性别：1 男，0 女 ,");
      }
    }
    if ((longitude != null) && (!"".equals(longitude)) && 
      (!DZStringUtil.verifyItude(longitude)))
    {
      isCheck = false;
      errorMsg.append("经度格式不合法 请设置为3位整数6位小数,");
    }
    if ((latitude != null) && (!"".equals(latitude)) && 
      (!DZStringUtil.verifyItude(latitude)))
    {
      isCheck = false;
      errorMsg.append("纬度格式不合法 请设置为3位整数6位小数,");
    }
    if (isCheck)
    {
      try
      {
        UserBaseVO userBaseVo = this.userDAO.getUserById(userId);
        if (userBaseVo != null)
        {
          userId = userBaseVo.getUserId();
          if (gender != null) {
            userBaseVo.setGender(Integer.valueOf(gender));
          }
          if (userName != null) {
            userBaseVo.setName(userName);
          }
          if (null != email) {
            userBaseVo.setEmail(email);
          }
          UserDetailVO userDetailVo = this.userDAO.getUserDetailByUserId(userId);
          if (null != nickName) {
            userDetailVo.setNickName(nickName);
          }
          if (null != districtCode) {
            userDetailVo.setDistrictCode(districtCode);
          }
          if (null != addDetail) {
            userDetailVo.setAddDetail(addDetail);
          }
          if (null != longitude) {
            userDetailVo.setLongitude(StringUtils.isNotBlank(longitude) ? Double.valueOf(longitude) : null);
          }
          if (null != latitude) {
            userDetailVo.setLatitude(StringUtils.isNotBlank(latitude) ? Double.valueOf(latitude) : null);
          }
          int baseRs = this.userDAO.updateUserByBase(userBaseVo);
          int detailRs = this.userDAO.updateUserByDetail(userDetailVo);
          if ((baseRs > 0) && (detailRs > 0)) {
            isSuccess = Integer.valueOf(1);
          }
        }
      }
      catch (Exception e)
      {
        LogUtil.error("更新用户资料数据发生异常", e);
        errorMsg.append("更新用户资料数据发生异常");
        isSuccess = Integer.valueOf(0);
        resObj.put("errorCode", DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value());
      }
    }
    else
    {
      isSuccess = Integer.valueOf(0);
      resObj.put("errorCode", DzErrorCode.UserErrorCode.BAD_PARAM_VERIFY.value());
      if (errorMsg.length() > 1) {
        errorMsg.deleteCharAt(errorMsg.length() - 1);
      }
    }
    resObj.put("isSuccess", isSuccess);
    if (isSuccess.intValue() == 0)
    {
      resObj.put("errorMsg", errorMsg);
    }
    else
    {
      resObj.put("userName", userName);
      resObj.put("userId", userId);
      resObj.put("nickName", nickName);
      resObj.put("gender", gender);
      

      resObj.put("districtCode", districtCode);
      resObj.put("addDetail", addDetail);
      resObj.put("longitude", longitude);
      resObj.put("latitude", latitude);
      resObj.put("email", email);
    }
    String resJson = JSON.toJSONString(resObj);
    return resJson;
  }
  
  public String queryUserDetail(String reqJson)
    throws Exception
  {
    JSONObject resObj = new JSONObject();
    boolean isCheck = true;
    Integer isSuccess = Integer.valueOf(0);
    StringBuffer errorMsg = new StringBuffer();
    JSONObject reqObj = JSON.parseObject(reqJson);
    
    String userId = reqObj.getString("userId");
    if ((userId == null) || ("".equals(userId)))
    {
      errorMsg.append("用户ID不能够为空");
      isCheck = false;
    }
    if (isCheck)
    {
      try
      {
        UserBaseVO userBaseVo = this.userDAO.getUserById(userId);
        Integer valid = userBaseVo != null ? userBaseVo.getIsValid() : null;
        if ((userBaseVo != null) && (valid != null) && (valid.intValue() == 1))
        {
          userId = userBaseVo.getUserId();
          String userName = userBaseVo.getName();
          Integer gender = userBaseVo.getGender();
          String notifyUrl = userBaseVo.getNotifyUrl();
          UserDetailVO userDetailVo = this.userDAO.getUserDetailByUserId(userId);
          


          String addDetail = userDetailVo.getAddDetail();
          Double longitude = userDetailVo.getLatitude();
          Double latitude = userDetailVo.getLatitude();
          isSuccess = Integer.valueOf(1);
          resObj.put("isSuccess", isSuccess);
          resObj.put("errorMsg", errorMsg);
          resObj.put("userName", userName);
          resObj.put("userId", userId);
          resObj.put("notifyUrl", notifyUrl);
          


          resObj.put("addDetail", addDetail);
          resObj.put("longitude", longitude);
          resObj.put("latitude", latitude);
          resObj.put("gender", gender);
        }
        else
        {
          LogUtil.error("未查询到客户详细信息;userID:" + userId);
          errorMsg.append("未查询到客户详细信息,请检查传入参数的正确性");
          resObj.put("isSuccess", isSuccess);
          resObj.put("errorMsg", errorMsg);
          resObj.put("errorCode", DzErrorCode.UserErrorCode.USER_NOT_FOUND.value());
        }
      }
      catch (Exception e)
      {
        LogUtil.error("客户详细信息查询发生异常", e);
        errorMsg.append("客户详细信息查询发生异常");
        resObj.put("isSuccess", isSuccess);
        resObj.put("errorMsg", errorMsg);
        resObj.put("errorCode", DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value());
      }
    }
    else
    {
      resObj.put("isSuccess", isSuccess);
      resObj.put("errorMsg", errorMsg);
      resObj.put("errorCode", DzErrorCode.UserErrorCode.BAD_PARAM_VERIFY.value());
    }
    String resJson = JSON.toJSONString(resObj);
    return resJson;
  }
  
  public String queryUserDetailByCard(String reqJson)
    throws Exception
  {
    JSONObject resultJson = new JSONObject();
    JSONObject reqObj = JSON.parseObject(reqJson);
    String cardNo = reqObj.getString("cardNo");
    String cardType = reqObj.getString("cardType");
    if (StringUtils.isBlank(cardNo))
    {
      resultJson.put("isSuccess", Integer.valueOf(0));
      resultJson.put("errorMsg", DzErrorCode.CommonErrorCode.PARAM_REQUIRED.getDesc() + ",卡号不能为空。");
      resultJson.put("errorCode", DzErrorCode.CommonErrorCode.PARAM_REQUIRED.value());
      return resultJson.toJSONString();
    }
    if (StringUtils.isBlank(cardType))
    {
      cardType = this.cardTypeService.getCardType(cardNo);
      if (StringUtils.isBlank(cardType))
      {
        resultJson.put("isSuccess", Integer.valueOf(0));
        resultJson.put("errorMsg", DzErrorCode.CommonErrorCode.PARAM_REQUIRED.getDesc() + ",卡类型不能为空。");
        resultJson.put("errorCode", DzErrorCode.CommonErrorCode.PARAM_REQUIRED.value());
        return resultJson.toJSONString();
      }
    }
    if (DzConstants.CardType.ONLINE_CARD.value().equals(cardType))
    {
      UserBaseVO ub = queryUserDetailByVirtualCard(cardNo);
      if (null == ub)
      {
        resultJson.put("isSuccess", Integer.valueOf(0));
        resultJson.put("errorMsg", DzErrorCode.UserErrorCode.USER_NOT_FOUND.getDesc());
        resultJson.put("errorCode", DzErrorCode.UserErrorCode.USER_NOT_FOUND.value());
        return resultJson.toJSONString();
      }
      return JSONObject.toJSONString(ub);
    }
    return "";
  }
  
  public UserBaseVO queryUserDetailByVirtualCard(String cardNo)
    throws Exception
  {
    UserBaseVO ub = this.userDAO.queryUserDetailByVirtualCard(cardNo);
    return ub;
  }
  
  protected String userIsExists(String reqJson)
    throws Exception
  {
    JSONObject resultJson = new JSONObject();
    try
    {
      JSONObject reqObj = JSON.parseObject(reqJson);
      String mobileNo = reqObj.getString("mobileNo");
      String merchantCode = reqObj.getString("merchantCode");
//      String merchantCode = "120161012";
//    String merchantCode = reqObj.getString("merchantCode");
      Integer isExists = Integer.valueOf(0);
      if (StringUtils.isBlank(mobileNo))
      {
        resultJson.put("isSuccess", Integer.valueOf(0));
        resultJson.put("errorCode", DzErrorCode.CommonErrorCode.PARAM_REQUIRED.value());
        resultJson.put("errorMsg", "手机号码不能为空。");
        return resultJson.toString();
      }
      if (StringUtils.isBlank(merchantCode))
      {
        resultJson.put("isSuccess", Integer.valueOf(0));
        resultJson.put("errorCode", DzErrorCode.CommonErrorCode.PARAM_REQUIRED.value());
        resultJson.put("errorMsg", "运营商编码不能为空。");
        return resultJson.toString();
      }
      UserBaseVO userBase = this.userDAO.getUserBaseByUserId(null, mobileNo, merchantCode);
      resultJson.put("isSuccess", Integer.valueOf(1));
      if (null != userBase) {
        isExists = DzConstants.Common.ONE;
      }
      resultJson.put("isExists", isExists);
      return resultJson.toJSONString();
    }
    catch (Exception e)
    {
      LogUtil.error("通过手机号和运营商编码查询用户是否存在异常", e);
      resultJson.put("isSuccess", Integer.valueOf(0));
      resultJson.put("errorCode", DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value());
      resultJson.put("errorMsg", "通过手机号和运营商编码查询用户是否存在异常。");
    }
    return resultJson.toString();
  }
  
  protected String queryCardState(String reqJson)
    throws Exception
  {
    JSONObject resultJson = new JSONObject();
    try
    {
      JSONObject reqObj = JSON.parseObject(reqJson);
      String cards = reqObj.getString("cardList");
      if (StringUtils.isBlank(cards))
      {
        resultJson.put("isSuccess", Integer.valueOf(0));
        resultJson.put("errorCode", DzErrorCode.CommonErrorCode.PARAM_REQUIRED.value());
        resultJson.put("errorMsg", "卡号列表不能为空");
        return resultJson.toJSONString();
      }
      List<String> cardList = JSON.parseArray(cards, String.class);
      if (CollectionUtils.isEmpty(cardList))
      {
        resultJson.put("isSuccess", Integer.valueOf(0));
        resultJson.put("errorCode", DzErrorCode.CommonErrorCode.PARAM_REQUIRED.value());
        resultJson.put("errorMsg", "卡号列表不能为空");
        return resultJson.toJSONString();
      }
      if (cardList.size() > 30)
      {
        resultJson.put("isSuccess", Integer.valueOf(0));
        resultJson.put("errorCode", DzErrorCode.CommonErrorCode.PARAM_TOO_LARGE.value());
        resultJson.put("errorMsg", "数据超过最大处理量30条。");
        return resultJson.toJSONString();
      }
      List<Map<String, Object>> rsList = this.userService.queryCardState(cardList);
      
      resultJson.put("isSuccess", Integer.valueOf(1));
      resultJson.put("cardList", rsList);
      return resultJson.toJSONString();
    }
    catch (Exception e)
    {
      LogUtil.error("查询卡状态异常", e);
      resultJson.put("isSuccess", Integer.valueOf(0));
      resultJson.put("errorCode", DzErrorCode.ExceptionErrorCode.COMMON_EXCEPTION.value());
      resultJson.put("errorMsg", "查询卡状态异常");
    }
    return resultJson.toString();
  }
}
